package com.newdream.annotation.aspect;

import com.newdream.annotation.annotation.NeedAssignment;
import com.newdream.annotation.util.BeanUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;

/**
 * @ author: sanglei
 * @ date: 2019-02-13 14:32
 * @ description:
 */
@Component
@Aspect
public class SetFieldValue {

    @Autowired
    private BeanUtil beanUtil;

    @Around("@annotation(com.newdream.annotation.annotation.NeedSetFieldValue)")
    public Object doSetValue(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("aop调用开始");
        Object[] args = pjp.getArgs();
        for(Object obj : args){
            System.out.println("arguments: "+obj);
            if(obj instanceof HttpServletRequest){
                System.out.println("request");
                HttpServletRequest request = (HttpServletRequest)obj;
                String sss = request.getHeader("sanglei");
                System.out.println("header中信息:"+sss);
            }else {
                Class clazz = obj.getClass();
                Field[] fields = clazz.getDeclaredFields();
                for(Field field:fields){
                    NeedAssignment needAssignment = field.getAnnotation(NeedAssignment.class);
                    if(null!=needAssignment){
                        field.setAccessible(true);
                        field.set(obj,"aaa");
                    }
                }
            }
        }
        Object ret  = pjp.proceed(args);
        //if(ret instanceof Collection){
        //    beanUtil.setFieldValueForCollection((Collection) ret);
        //}else {
        //    beanUtil.setApplicationContext(null);
        //}
        System.out.println("aop调用完成");
        return ret;
    }
}
